import { Form, Input, Button, message, Space } from "antd";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import { v4 as uuidv4 } from "uuid";

import useCheckCategoryByCcName from "../../hooks/category/useCheckCategoryByCcName";
import useCreateCategory from "../../hooks/category/useCreateCategory";

const AddCommodityClassModle = (props) => {
    const { onCloseGlobalModal } = useModel("global.modal");
    const { checkCategoryName } = useCheckCategoryByCcName();
    const { createCategory } = useCreateCategory();
    const [form] = Form.useForm();

    const state = useReactive({
        submitLoading: false,
    });

    const onFinish = async (values) => {
        state.submitLoading = true;
        let saveDate = {
            ccPaid: null,
            ccUuid: uuidv4(),
            ccName: values.ccName,
        };
        let res = await createCategory(saveDate);
        if (res) {
            form.resetFields();
            message.success("成功创建品类信息");
            reloadData();
            onCloseGlobalModal();
        }
        state.submitLoading = false;
    };

    const ccNameValidator = async (rule, value) => {
        if (value && validates.titleAndName(value) && value.length < 31) {
            let res = await checkCategoryName({ oiName: value });
            if (res === null) return Promise.reject("检查品类名称出错");
            return res > 0 ? Promise.reject("品类名称重复！") : Promise.resolve();
        } else {
            return Promise.reject("品类名称只能输入中文、英文、数字，最多30个汉字");
        }
    };

    return (
        <div>
            <Form form={form} layout="horizontal" onFinish={onFinish} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
                <Form.Item label="品类名称" name="ccName" validateTrigger="onBlur" rules={[{ required: true, validator: ccNameValidator }]}>
                    <Input placeholder="请输入品类名称" />
                </Form.Item>

                <div style={{ marginTop: 20, textAlign: "center" }}>
                    <Space>
                        <Button loading={state.submitLoading} type="primary" htmlType="submit" style={{ width: "100%" }}>
                            提交
                        </Button>
                        <Button loading={state.submitLoading} onClick={onCloseGlobalModal}>
                            取消
                        </Button>
                    </Space>
                </div>
            </Form>
        </div>
    );
};

export default AddCommodityClassModle;
